package com.example.sharding.service.impl;



import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.sharding.dao.TAnnotationDataItemMapper;
import com.example.sharding.enerty.TAnnotationDataItem;
import com.example.sharding.service.TAnnotationDataItemService;
import com.example.sharding.utils.DictEnum;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @program: test_demo
 * @description: 数据字典业务层
 * @author: yanghua
 * @create: 2021-11-04 19:57
 **/
@Service
public class TAnnotationDataItemServiceImpl extends ServiceImpl<TAnnotationDataItemMapper, TAnnotationDataItem> implements TAnnotationDataItemService {
    @Resource
    private  TAnnotationDataItemMapper tannotationDataItemMapper;

    @Override
    @Cacheable(value = DictEnum.REDIS_DICT_CACHE, key = "#dataSource+'-'+#key")
    public String selectByDatasourceKey(String dataSource, String key) {
        LambdaQueryWrapper<TAnnotationDataItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TAnnotationDataItem::getDatasource,dataSource);
        queryWrapper.eq(TAnnotationDataItem::getCode,key);

        List<TAnnotationDataItem> tannotationDataItems = tannotationDataItemMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(tannotationDataItems)){
            return "";
        }
        return tannotationDataItems.get(0).getVal();
    }
    @Override
    @Cacheable(value = DictEnum.REDIS_DICT_CACHE, key = "#dataSource")
    public Map<String, List<TAnnotationDataItem>> selectByDatasourceKeyBanch(String dataSource) {

        LambdaQueryWrapper<TAnnotationDataItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StrUtil.isNotBlank(dataSource),TAnnotationDataItem::getDatasource,dataSource);
        List<TAnnotationDataItem> tannotationDataItems = tannotationDataItemMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(tannotationDataItems)){
            return null;
        }

        Map<String, List<TAnnotationDataItem>> listMap = tannotationDataItems.stream().
                collect(Collectors.groupingBy(TAnnotationDataItem::getCode));

        return listMap;
    }
}
